#include "timerevent.h"
#include "coreutils.h"

TimerEvent::TimerEvent()
{
    eventModel = new QSqlQueryModel(this);

    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(checkEvent()));
}


TimerEvent::~TimerEvent()
{
}


void TimerEvent::run()
{
    TimerEvent *timerEvent = new TimerEvent();
    timerEvent->refresh();
    timerEvent->timer->start(1000);
}


void TimerEvent::refresh()
{
    QSqlQuery query;
    query.prepare("SELECT *, "
                  "( CASE WHEN EventTime IS NULL "
                  "THEN "
                       "(CASE WHEN SuspendDate IS NULL "
                       "THEN strftime('%Y-%m-%d %H:%M:%S', RemindDate || ' ' || '00:00:00') "
                       "ELSE SuspendDate "
                       "END) "
                  "ELSE strftime('%Y-%m-%d %H:%M:%S', RemindDate || ' ' || EventTime) "
                  "END ) AS EventDateTime "
                  "FROM "
                  "(SELECT *, "
                  "(CASE WHEN RemindBefore IS NULL "
                  "THEN strftime('%Y', 'now') || '-' || strftime('%m-%d', EventDate) "
                  "ELSE date(strftime('%Y', 'now') || '-' || strftime('%m-%d', EventDate), '-' || RemindBefore || ' day') "
                  "END) AS RemindDate "
                  "FROM Event "
                  "WHERE RemindDate <= strftime('%Y-%m-%d', 'now') "
                  "AND RemindDate > strftime('%Y-%m-%d', 'now', '-7 days') "
                  "AND (NOT EventApply = 1 OR EventApply IS NULL)) "
                  "ORDER BY EventDateTime");
    query.exec();
    CoreUtils::checkQuery(query);
    eventModel->setQuery(query);
}


void TimerEvent::checkEvent()
{
    int rowCount = eventModel->rowCount();
    if (rowCount <= 0)
        qDebug() << "no events";
    else
        qDebug() << "rowcount:" + QString::number(rowCount);

//    qDebug() << "check date (rowcount:" + QString::number(rowCount) + ")";
//    qDebug() << "next event: " + eventModel->record(0).value("EventDate").toString() + " "
//            + eventModel->record(0).value("EventTime").toString();

    for (int i = 0; i < rowCount; i++) {
        QDateTime eventDateTime = eventModel->record(i).value("EventDateTime").toDateTime();
        int eventId = eventModel->record(i).value("EventId").toInt();
        if (eventDateTime <= QDateTime::currentDateTime()
            && (showCodes.indexOf(eventId) == -1)) {
            showCodes = EventMessage::run(eventId, this);
        }
    }

    int rowIndex = 0;
    if (rowCount > 1)
        while (rowIndex < rowCount) {
        qDebug() << eventModel->record(rowIndex).value("EventDate").toString()
                + " " + eventModel->record(rowIndex).value("EventTime").toString();
        rowIndex++;
    }

}
